<template>
  <el-dialog
    v-if="open"
    :title="title"
    v-model="open"
    draggable
    :close-on-click-modal="false"
    width="70%"
    append-to-body
    :before-close="cancel"
  >
    <div class="dialog-container">
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="128px"
      >
        <el-form-item label="工艺段名称" prop="sectionCodes">
          <el-select
            v-model="queryParams.sectionCodes"
            placeholder="请选择"
            clearable
            filterable
            multiple
            collapse-tags
            style="width: 240px"
          >
            <el-option
              v-for="(item, index) in sectionList"
              :key="index"
              :label="item.deptName"
              :value="item.deptCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单编号" prop="orderCode">
          <el-input
            v-model="queryParams.orderCode"
            placeholder="请输入订单编号"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="prodName">
          <el-input
            v-model="queryParams.prodName"
            placeholder="请输入产品名称"
            clearable
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="选择时间段" prop="date">
          <el-date-picker
            v-model="queryParams.date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        :data="typeList"
        border
        max-height="400px"
        @select="handleSelectionChange"
        @select-all="selectAll"
        ref="workOrderTable"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="订单编号" prop="orderCode" width="140" />
        <el-table-column label="产品编号" prop="prodCode" />
        <el-table-column label="产品名称" prop="prodName" />
        <el-table-column label="计划产量" prop="planNumber" />
        <el-table-column label="已完工数量" prop="actualNumber" />
        <el-table-column label="单位" prop="unit" />
        <el-table-column label="计划开始时间" prop="planStartTime">
          <template #default="scope">
            <span>{{ scope.row.planStartTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划结束时间" prop="planEndTime">
          <template #default="scope">
            <span>{{ scope.row.planEndTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工艺段" prop="sectionName" />
        <el-table-column label="来源" prop="source">
          <template #default="scope">
            <dict-tag :options="order_source" :value="scope.row.source" />
          </template>
        </el-table-column>

        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <dict-tag :options="work_order_status" :value="scope.row.status" />
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="UserSelect">
import { toRefs } from "vue";
import { listOrder } from "@/api/base/workOrder/workOrder";
import { ref, nextTick, reactive, watch, getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
const { work_order_status } = proxy.useDict("work_order_status");
const { order_source } = proxy.useDict("order_source");
const props = defineProps([
  "placeholder",
  "title",
  "multiple",
  "openWorkOrder",
  "sectionCodeList",
  "sectionList",
  "factory",
  "workshopCode",
  "lineCode",
  "hasSelectedWorkOrderList",
]);
const {
  title,
  openWorkOrder,
  sectionCodeList,
  sectionList,
  factory,
  workshopCode,
  lineCode,
  hasSelectedWorkOrderList,
} = toRefs(props);
const emit = defineEmits(["change"]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);

const total = ref(0);
const arrInfoSelection = ref([]);
const workOrderTable = ref();
const typeList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: "IN_PRODUCTION",
    deptCode: undefined,
    sectionCodes: undefined,
    factory,
    workshopCode,
    lineCode,
  },
});

const { queryParams } = toRefs(data);

watch(
  openWorkOrder,
  (val) => {
    open.value = val;
    queryParams.value.sectionCodes = sectionCodeList.value;
    arrInfoSelection.value = [];
    if (val == true) {
      getList();
      if (hasSelectedWorkOrderList.value && hasSelectedWorkOrderList.value.length > 0) {
        arrInfoSelection.value = hasSelectedWorkOrderList.value;
      }
    }
  },
  { immediate: true, deep: true }
);

function getList() {
  loading.value = true;
  let newForm = JSON.parse(JSON.stringify(queryParams.value));
  if (queryParams.value?.date?.length) {
    newForm.planStartTime = queryParams.value.date[0] + " 00:00:00";
    newForm.planEndTime = queryParams.value.date[1] + " 23:59:59";
    delete newForm.date;
  }
  if (queryParams.value?.sectionCodes?.length) {
    newForm.sectionCodes = queryParams.value.sectionCodes.toString();
  } else {
    newForm.sectionCodes = sectionCodeList.value.toString();
  }
  listOrder(proxy.addDateRange(newForm)).then((response) => {
    typeList.value = response.rows;
    total.value = response.total;
    loading.value = false;

    nextTick(() => {
      if (typeList.value.length && arrInfoSelection.value.length) {
        typeList.value.forEach((item) => {
          const include = arrInfoSelection.value.filter((info) => info.id == item.id);
          if (include.length) {
            workOrderTable.value.toggleRowSelection(item, true);
          } else {
            workOrderTable.value.toggleRowSelection(item, false);
          }
        });
      }
    });
  });
}

function submitForm() {
  if (arrInfoSelection.value?.length && arrInfoSelection.value.length > 0) {
    emit("changeWorkOrderList", JSON.parse(JSON.stringify(arrInfoSelection.value)));
  } else {
    proxy.$modal.msgError("请选择至少一条生产订单！");
  }
}
function cancel() {
  emit("changeWorkOrderList", []);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.sectionCodes = null;
  queryParams.value.date = [];
  handleQuery();
}

/** 选择条数  */
function handleSelectionChange(selection, row) {
  // selectData.value = selection;
  let selected = selection.length && selection.indexOf(row) !== -1;
  if (selected) {
    arrInfoSelection.value.push(row);
  } else {
    arrInfoSelection.value = arrInfoSelection.value.filter((item) => item.id != row.id);
  }
}

// 全选 或全不选
function selectAll(section) {
  if (section.length) {
    // 全选  push
    section.forEach((item) => {
      arrInfoSelection.value.push(item);
    });
  } else {
    // 全不选  当页数据  删除
    if (typeList.value.length && arrInfoSelection.value.length) {
      typeList.value.forEach((item) => {
        arrInfoSelection.value = arrInfoSelection.value.filter((info) => item.id != info.id);
      });
    }
  }
  arrInfoSelection.value = uniqueObjects(arrInfoSelection.value);
}

// 数组对象去重
function uniqueObjects(arr) {
  const seen = new Map();
  return arr.filter((item) => {
    // 将对象转换为字符串（或其他可以唯一表示对象的内容）
    const key = JSON.stringify(item);
    // 如果 Map 中还没有这个键，则添加它并返回 true
    if (!seen.has(key)) {
      seen.set(key, item);
      return true;
    }
    // 如果已经有了，就返回 false，表示这个对象应该被过滤掉
    return false;
  });
}
</script>
